<?php
require_once 'common/config.php';
require_once 'common/functions.php';
// 检查登录状态
check_login();
$db = db_connect();
// 处理删除操作
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    try {
        // 获取帖子信息以删除图片
        $stmt = $db->prepare("SELECT image FROM posts WHERE id = ?");
        $stmt->execute([$id]);
        $post = $stmt->fetch();       
        // 开始事务
        $db->beginTransaction();       
        // 先删除相关的评论
        $stmt = $db->prepare("DELETE FROM comments WHERE post_id = ?");
        $stmt->execute([$id]);      
        // 再删除帖子
        $stmt = $db->prepare("DELETE FROM posts WHERE id = ?");
        $stmt->execute([$id]);     
        // 提交事务
        $db->commit();
        // 如果有图片，删除图片文件
        if ($post && $post['image']) {
            $image_path = '../api/user/' . $post['image'];
            if (file_exists($image_path)) {
                unlink($image_path);
            }
        }
        redirect('posts.php', '帖子删除成功');
    } catch (Exception $e) {
        // 回滚事务
        $db->rollBack();
        redirect('posts.php', '删除失败：' . $e->getMessage(), 'error');
    }
}
// 获取搜索和状态参数
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status = isset($_GET['status']) ? intval($_GET['status']) : -1;
// 每页显示的记录数
$per_page = 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $per_page;
// 构建查询条件
$where = "1=1";
$params = [];
if ($search) {
    $where .= " AND (p.title LIKE :search OR p.content LIKE :search OR u.name LIKE :search)";
    $params[':search'] = "%{$search}%";
}
if ($status !== -1) {
    $where .= " AND p.status = :status";
    $params[':status'] = $status;
}
// 获取总记录数
$count_sql = "SELECT COUNT(*) FROM posts p 
              LEFT JOIN users u ON p.user_id = u.id 
              WHERE {$where}";
$count_stmt = $db->prepare($count_sql);
foreach ($params as $key => $value) {
    $count_stmt->bindValue($key, $value);
}
$count_stmt->execute();
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $per_page);
// 获取帖子列表
$sql = "SELECT p.*, u.name as user_name, 
        COUNT(c.id) as comment_count 
        FROM posts p 
        LEFT JOIN users u ON p.user_id = u.id 
        LEFT JOIN comments c ON p.id = c.post_id 
        WHERE {$where} 
        GROUP BY p.id 
        ORDER BY p.created_at DESC
        LIMIT {$offset}, {$per_page}";
$stmt = $db->prepare($sql);
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();
$posts = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>帖子管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="../admin/assets/js/jquery.min.js"></script>
</head>
<body>
    <div class="wrapper">
        <?php include 'includes/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="content">
                <h2>帖子管理</h2>
                
                <!-- 搜索和筛选 -->
                <div class="filter-bar">
                    <form action="" method="GET" id="searchForm" class="search-bar">
                        <div class="search-input">
                            <input type="text" name="search" placeholder="搜索帖子标题、内容、发帖人..." 
                                   value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="status-select">
                            <select name="status" id="status-select" onchange="document.getElementById('searchForm').submit()">
                                <option value="-1">全部状态</option>
                                <option value="1" <?php echo ($status === 1) ? 'selected' : ''; ?>>正常</option>
                                <option value="0" <?php echo ($status === 0) ? 'selected' : ''; ?>>已隐藏</option>
                            </select>
                        </div>
                        <button type="submit" class="btn-search">
                            <i class="fas fa-search"></i>
                        </button>
                    </form>
                </div>

                <!-- 帖子列表 -->
                <div class="data-table">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>标题</th>
                                <th>图片</th>
                                <th>发帖人</th>
                                <th>浏览量</th>
                                <th>点赞数</th>
                                <th>评论数</th>
                                <th>发布时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($posts as $post): ?>
                            <tr>
                                <td><?php echo $post['id']; ?></td>
                                <td><?php echo htmlspecialchars($post['title']); ?></td>
                                <td>
                                    <?php if ($post['image']): ?>
                                    <img src="<?php echo '../api/user/' . $post['image']; ?>" 
                                         alt="帖子图片" 
                                         style="max-width: 50px; max-height: 50px;"
                                         onclick="showImage(this.src)">
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($post['user_name']); ?></td>
                                <td><?php echo $post['view_count']; ?></td>
                                <td><?php echo $post['like_count']; ?></td>
                                <td><?php echo $post['comment_count']; ?></td>
                                <td><?php echo date('Y-m-d H:i', strtotime($post['created_at'])); ?></td>
                                <td>
                                    <span class="badge badge-<?php echo $post['status'] ? 'success' : 'danger'; ?>">
                                        <?php echo $post['status'] ? '正常' : '禁用'; ?>
                                    </span>
                                </td>
                                <td>
                                    <a href="post_detail.php?id=<?php echo $post['id']; ?>" class="btn-icon" title="查看">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="post_edit.php?id=<?php echo $post['id']; ?>" class="btn-icon" title="编辑">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="javascript:void(0)" onclick="deletePost(<?php echo $post['id']; ?>)" class="btn-icon text-danger" title="删除">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- 添加分页 -->
                <?php 
                echo generate_pagination($page, $total_pages, [
                    'search' => $search
                ]); 
                ?>
            </div>
        </div>
    </div>

    <!-- 图片预览模态框 -->
    <div id="imageModal" class="modal" onclick="this.style.display='none'">
        <img id="modalImage" class="modal-content">
    </div>

    <script>
    function deletePost(id) {
        if (confirm('确定要删除这个帖子吗？相关的评论也会被删除。')) {
            window.location.href = `posts.php?action=delete&id=${id}`;
        }
    }

    function showImage(src) {
        const modal = document.getElementById('imageModal');
        const modalImg = document.getElementById('modalImage');
        modal.style.display = "block";
        modalImg.src = src;
    }
    </script>

    <style>
    /* 模态框样式 */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        padding-top: 50px;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.9);
        cursor: pointer;
    }

    .modal-content {
        margin: auto;
        display: block;
        max-width: 80%;
        max-height: 80%;
    }

    .filter-bar {
        background: #fff;
        margin-top: 10px;
        padding: 10px;
        border-radius: 4px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        margin-bottom: 20px;
    }

    .search-bar {
        display: flex;
        margin-top: 12px;
        align-items: center;
        gap: 8px;
    }

    .search-input {
        flex: 1;
    }

    .search-input input {
        width: 100%;
        padding: 6px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        line-height: 1.5;
        background: #f8f9fa;
        transition: all 0.3s;
    }

    .search-input input:focus {
        border-color: #3498db;
        background: #fff;
        outline: none;
    }

    .status-select select {
        padding: 6px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        line-height: 1.5;
        background: #f8f9fa;
        min-width: 100px;
        cursor: pointer;
        transition: all 0.3s;
    }

    .status-select select:focus {
        border-color: #3498db;
        background: #fff;
        outline: none;
    }

    .btn-search {
        padding: 6px 16px;
        background: #3498db;
        color: #fff;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        line-height: 1.5;
        transition: background 0.3s;
    }

    .btn-search:hover {
        background: #2980b9;
    }

    /* 响应式布局 */
    @media (max-width: 768px) {
        .search-bar {
            flex-direction: column;
        }
        
        .search-input,
        .status-select,
        .btn-search {
            width: 100%;
        }
        
        .status-select select {
            width: 100%;
        }
    }
    </style>

    <script>
    </script>
</body>
</html> 